<template>
  <transition name="message">
    <div
      class="notify-container"
      v-if="show"
      @mouseenter="clearTask"
      @mouseleave="closeNotify(duration)"
    >
      <div class="notify-container-content">
        <i
          :class="'el-icon-' + type"
          :style="{ color: iconColor, marginRight: '6px' }"
        ></i
        >{{ message }}
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "index",
  props: {
    message: String,
    duration: {
      type: Number,
      default: 2000
    },
    type: {
      type: String,
      default: "success"
    },
    icon: String
  },
  data() {
    return {
      show: false,
      closeNotifyTask: null,
      iconColor: "#fff"
    };
  },
  methods: {
    closeNotify(duration) {
      if (duration === 0) return;
      this.closeNotifyTask = setTimeout(() => {
        this.show = false;
      }, this.duration);
    },
    showNotify() {
      this.show = true;
      this.closeNotify(this.duration);
    },
    clearTask() {
      clearTimeout(this.closeNotifyTask);
    },
    /**
     * 根据type设置icon，如果type===undefined则默认为success
     * @param type
     */
    setColorByType(type = this.type) {
      switch (type) {
        case "success": {
          this.iconColor = "#67C23A";
          break;
        }
        case "warning": {
          this.iconColor = "#E6A23C";
          break;
        }
        case "error": {
          this.iconColor = "#F56C6C";
          break;
        }
        default: {
          this.iconColor = "#909399";
        }
      }
    }
  },
  beforeDestroy() {
    this.clearTask();
  },
  mounted() {
    this.showNotify();
    this.setColorByType();
  }
};
</script>

<style lang="scss" scoped>
.notify-container {
  position: fixed;
  left: 50%;
  transform: translate(-50%);
  background-color: #fff;
  border-radius: 3px;
  top: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  z-index: 1000;

  .notify-container-content {
    line-height: 1;
    padding: 8px 18px;
    font-size: 12px;
  }
}

.message-enter-active,
.message-leave-active {
  transition: all 0.3s ease;
}

.message-enter,
.message-leave-to {
  opacity: 0;
  top: 0;
}
</style>
